package com.hqyj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hqyj.dao.*;
import com.hqyj.pojo.*;
import com.hqyj.service.IPurchaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 进货表 服务实现类
 * </p>
 *
 * @author rock
 * @since 2021-10-21
 */
@Service
public class PurchaseServiceImpl implements IPurchaseService {

    //注入PurchaseMapper
    @Autowired(required = false)
    PurchaseMapper purchaseMapper;

    //注入StorehouseMapper
    @Autowired(required = false)
    StorehouseMapper storehouseMapper;

    //注入WarehousingMapper
    @Autowired(required = false)
    WarehousingMapper warehousingMapper;

    //注入UserMapper
    @Autowired(required = false)
    UserMapper userMapper;

    //注入TuihuoMapper
    @Autowired(required = false)
    TuihuoMapper tuihuoMapper;

    //注入RowsMapper
    @Autowired(required = false)
    RowsMapper rowsMapper;

    //注入ExpenditureMapper
    @Autowired(required = false)
    ExpenditureMapper expenditureMapper;

    @Override
    public HashMap<String, Object> select(Purchase purchase) {
        //创建HashMap对象
        HashMap<String,Object> map = new HashMap<>();
        //创建分页对象
        Page<Purchase> page = new Page<>(purchase.getPage(),purchase.getRow());

        //定义条件构造器
        QueryWrapper<Purchase> queryWrapper = new QueryWrapper<>();
        //查询数据库
        Page<Purchase> rowsPageList = purchaseMapper.selectPage(page, queryWrapper);
        //定义当前页集合
        map.put("list",rowsPageList.getRecords());
        //总页数
        map.put("totalPage",rowsPageList.getPages());
        //总条数
        map.put("total",rowsPageList.getTotal());
        //当前页
        map.put("curPage",purchase.getPage());
        //如果当前页为1，则上一页为也为1
        if (rowsPageList.getCurrent() == 1){
            //上一页
            map.put("prePage",1);
        }else {
            map.put("prePage",purchase.getPage()-1);
        }
        //如果当前页为最后一页，则下一页为也为最大页
        if (purchase.getPage() == rowsPageList.getPages()){
            //下一页
            map.put("nextPage",rowsPageList.getPages());
        }else {
            map.put("nextPage",purchase.getPage()+1);
        }
        //显示每页条数
        map.put("row",purchase.getRow());
        return map;
    }


    @Override
    public HashMap<String, Object> add(Purchase purchase) {
        //创建HashMap对象
        HashMap<String,Object> map = new HashMap<>();
        //
        return null;
    }

    //入库
    @Override
    public HashMap<String, Object> goWarehouse(Purchase purchase, HttpSession session) {
        //创建HashMap对象
        HashMap<String,Object> map = new HashMap<>();

        //条件构造器
        QueryWrapper<Storehouse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rows_id",purchase.getRowsId());
        //查询库存是否存在待入库食材
        List<Storehouse> storehouseList = storehouseMapper.selectList(queryWrapper);
        System.err.println(storehouseList);
        if (storehouseList.size()==0){
            System.out.println("调用添加方法");
            //创建Storehouse
            Storehouse storehouse = new Storehouse();
            //设置原料名字
            storehouse.setRowsName(purchase.getRowsName());
            //设置原料ID
            storehouse.setRowsId(purchase.getRowsId());
            //设置原料类别
            storehouse.setCategoryName("2");
            //设置库存参数
            storehouse.setStorehouseNum(new BigDecimal(purchase.getPurchaseNum()));
            //设置库存危险值
            storehouse.setDangerous(new BigDecimal("20"));
            storehouseMapper.insert(storehouse);
        }else {
            System.out.println("调用修改方法");
            //调用修改条件构造器
            UpdateWrapper<Storehouse> updateWrapper = new UpdateWrapper<>();
            //创建Storehouse对象，更新指定食材的库存数量
            Storehouse storehouse = new Storehouse();
            //更新指定食材的库存数量
            storehouse.setStorehouseNum(storehouseList.get(0).getStorehouseNum().add(new BigDecimal(purchase.getPurchaseNum() + "")));
            //修改条件
            updateWrapper.eq("rows_id",purchase.getRowsId());
            int num = storehouseMapper.update(storehouse, updateWrapper);
            if (num > 0){
                map.put("info","保存成功");
               //入库成功，修改进货单的状态为“已入库”
                //调用修改条件构造器
                UpdateWrapper<Purchase> updateWrapper1 = new UpdateWrapper<>();
                //修改状态
                purchase.setPurchaseState("已入库");
                //修改条件
                updateWrapper1.eq("purchase_id",purchase.getPurchaseId());
                //修改
                purchaseMapper.update(purchase,updateWrapper1);


                //生成入库记录表
                //创建入库单表
                Warehousing warehousing = new Warehousing();
                //设置进货表ID
                warehousing.setPurchaseId(purchase.getPurchaseId());
                //设置操作员ID
                User user = (User) session.getAttribute("USER");
                List<User> users = userMapper.selectByName(user.getSysName());
                Integer sysId = users.get(0).getSysId();
                warehousing.setSysId(sysId);
                //设置入库时间
                warehousing.setWarehousingTime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
                warehousingMapper.insert(warehousing);

                System.err.println("ABC");
                //生成支出表
                Expenditure expenditure = new Expenditure();
                //设置操作员ID
                expenditure.setSysId(sysId);
                //设置总金额
                    //1.1获取单价
                Rows rows = rowsMapper.selectById(purchase.getRowsId());
                    //1.2、单价*数量=总价
                expenditure.setExpenditureMoney((rows.getRowsMoney()).multiply(new BigDecimal(purchase.getPurchaseNum())));
                //设置时间
//                expenditure.setExpenditureTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                expenditure.setExpenditureTime(new Date());
                //设置备注
                expenditure.setBeizhu("购买"+purchase.getRowsName()+"花了"+expenditure.getExpenditureMoney()+"元钱！！");
                //存入数据库
                expenditureMapper.insert(expenditure);
            }else {
                map.put("info","保存失败");
            }
        }
        return map;
    }

    //退货
    @Override
    public HashMap<String, Object> returnedGoods(Purchase purchase,HttpSession session) {
        //创建HashMap对象
        HashMap<String,Object> map = new HashMap<>();
        //调用退货表的添加方法
        Tuihuo tuihuo = new Tuihuo();
        //设置操作员ID
        User user = (User) session.getAttribute("USER");
        List<User> users = userMapper.selectByName(user.getSysName());
        Integer sysId = users.get(0).getSysId();
        tuihuo.setSysId(sysId);
        //设置退货编号
        tuihuo.setPurchaseId(purchase.getPurchaseId());
        tuihuo.setTuihuoTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //调用方法
        int num = tuihuoMapper.insert(tuihuo);
        if (num > 0){
            map.put("info","保存成功");
            //退货成功，修改进货单的状态为“已退货”
            //调用修改条件构造器
            UpdateWrapper<Purchase> updateWrapper1 = new UpdateWrapper<>();
            //修改状态
            purchase.setPurchaseState("已退货");
            //修改条件
            updateWrapper1.eq("purchase_id",purchase.getPurchaseId());
            //修改
            purchaseMapper.update(purchase,updateWrapper1);

        }else {
            map.put("info","保存失败");
        }
        return map;
    }
}
